import requests
import re


class RegistTY:
    def __init__(self, username, password, repassword, verifyCode='aaaa',
                 url='http://192.168.10.139/ty17/TinyShop_v1.7'):
        self.session = requests.session()
        self.username = username
        self.password = password
        self.repassword = repassword
        self.verifyCode = verifyCode
        self.url = url

    def FitstPage(self):
        url = '%s/index.php' % self.url
        self.session.get(url)
        self.PHPSESSID = 'PHPSESSID=' + self.session.cookies[
            'PHPSESSID'] + ';safecode=a.txt;Tiny_autologin=dedfa36c3cMjA0MDAwMDMwMGJhMjU0PT4xNDVjOGRlMjAwZDJlZ2M'

    def GetTken(self):
        tokenurl = '%s/index.php?con=simple&act=reg' % self.url
        tokenheaders = {
            'Cookie': self.PHPSESSID
        }
        tokenhtml = self.session.get(tokenurl, headers=tokenheaders).text
        passent = re.compile(r"<input type='hidden' name='tiny_token_reg' value='(.*)'/>")
        self.token = passent.findall(tokenhtml)[0]
        print(self.token)

    def GetNewToken(self):
        tokenurl = '%s/index.php?con=simple&act=reg_act' % self.url
        tokendata = {
            'email': self.username,
            'password': self.password,
            'repassword': self.repassword,
            'tiny_token_reg': self.token
        }
        tokenheaders = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Cookie': self.PHPSESSID,
            'Referer': '%s/index.php?con=simple&act=reg' % self.url
        }
        self.tokenhtml = requests.post(tokenurl, headers=tokenheaders, data=tokendata).text

    def compfile(self):
        passent = re.compile(r'<input type="hidden" name="user_name" value="(.*)" /><input type="hidden"')
        content = passent.findall(self.tokenhtml)[0]
        if content == self.username:
            self.res = '注册成功'
        else:
            self.res = '注册失败'

    def start(self):
        try:
            self.FitstPage()
            self.GetTken()
            self.GetNewToken()
            self.compfile()
        except Exception:
            self.res = '注册失败'
        return self.res


if __name__ == "__main__":
    RegistTY('25377541136888@qq.com', '123456', '123456').start()
